package com.study.spring.ch03.controller;

import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.study.spring.ch03.pojo.User;
import com.study.spring.ch03.pojo.UserModel;

@Controller
@RequestMapping(value="/ch03/modelAttr/**") //①处理器的通用映射前缀
public class ModelAttrBindController {

	/**
	 * http://127.0.0.1:8080/spring/ch03/modelAttr/model01?username=123abc
	 * @return
	 */
	@RequestMapping(value="model01", method=RequestMethod.GET)
	public String reqParamBind01(@ModelAttribute("user") UserModel user) {
		System.out.println("================modelAttr:"+user);
		return "ch03/create";
	}
	
	/**
	 * http://127.0.0.1:8080/spring/ch03/modelAttr/model02/zhang
	 * @return
	 */
	@RequestMapping(value="/model02/{username}", method=RequestMethod.GET)
	public String reqParamBind02(@ModelAttribute("user") UserModel user) {
		System.out.println("================modelAttr:"+user);
		return "ch03/create";
	}
	
	/**
	 * http://127.0.0.1:8080/spring/ch03/modelAttr
	 * /model03?username=zhang&password=123&workInfo.city=bj
	 * @return
	 */
	@RequestMapping(value="/model03", method=RequestMethod.GET)
	public String reqParamBind03(@ModelAttribute("user") UserModel user) {
		System.out.println("================modelAttr:"+user);
		return "ch03/create";
	}
	
	/**
	 * ①
	 * ModelAttribute:暴露表单引用对象为模型数据
	 * @return
	 */
	@ModelAttribute("cityList")
	public List<String> cityList() {
		return Arrays.asList("北京", "山东");
	}

	/**
	 * http://127.0.0.1:8080/spring/ch03/modelAttr//model04/list1
	 * 触发 上面的cityList 方法触发
	 * @param m
	 * @return
	 */
	@RequestMapping("/model04/list1")
	public ModelAndView handleRequest(Model m) {
		  List<String> list = (List<String>)m.asMap().get("cityList");
		  for(String s : list){
		    System.out.println("s==="+s);
		  }
		return null;
	}
	
	/**
	 * http://127.0.0.1:8080/spring/ch03/modelAttr//model05/test?username=zhangsan&password=123
	 * @param username
	 * @return
	 */
	@ModelAttribute("user") //①
	public User getUser(@RequestParam(value="username", defaultValue="") String username) {
		User user = new User();
		user.setUsername(username + "from method");
		user.setPassword("pw from method");
		return user; 
	}
	
	/**
	 * http://127.0.0.1:8080/spring/ch03/modelAttr//model05/test?username=zhangsan&password=123
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/model05/test") //②
	public String test1(@ModelAttribute("user") User user, Model model){
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
		
		return "login.jsp";
		
	}
}


